package com.bestdata.TD440.util;

import org.apache.logging.log4j.util.Strings;

import java.util.ArrayList;
import java.util.List;

/**
 * @author
 */
public class CRC16Util {

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] hex2Bytes(String str) {
        if(str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }

    //CRC16  校验码验证
    public static String CRC16(String dataHexStr)
    {
        byte[] data = CRC16Util.hex2Bytes(dataHexStr);
        int crci=0x0000ffff;   //起始字节ffff
        int i,j;
        for ( j = 0; j < data.length; j++)
        {
            crci ^= data[j] & 0x000000ff;
            for ( i = 0; i < 8; i++){
                if ((crci & 0X00000001) != 0){
                    crci >>= 1;
                    crci ^= 0x0000a001;    //多项式当中的那个啥的，不同多项式不一样
                }else{
                    crci >>= 1;
                }
            }
        }
        String res  = Integer.toHexString(crci);//((byte)crci ^ 0x0000);
        return res;
    }

    public static String str2HexStr(String str)
    {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;

        for (int i = 0; i < bs.length; i++)
        {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 振动采集CRC16校验
     * @author chizhenyu
     * @return
     */
    public static Integer CRC16XOR(String resData){

        byte[] bytes = hexStringToByteArray(resData);

        int temp = 0;
        for (int i =0;i< bytes.length; i++) {
            temp ^= bytes[i];
        }
        return temp;
    }

    public static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
                    .digit(hexString.charAt(i+1), 16));
        }
        return bytes;
    }

}
